Imports MIMS.WRS.Business
Imports MIMS.WRS.Entities
Imports System.Data
Imports System.Data.Common
Imports System.Net
Imports System
Imports System.IO
Imports System.Text
Imports MyFramework

Public Class CustomerOrders

    Inherits System.Web.UI.Page

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents grdCustomerOrder As System.Web.UI.WebControls.DataList

    Protected WithEvents btnBack As System.Web.UI.WebControls.Button
    Protected WithEvents btnPrint As System.Web.UI.WebControls.Button

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Protected currentOrder As Integer = 1

    Private Const ONE_VOLUME_CBM_TO_CUFT As Double = 35.31
    Private Const ONE_KG_TO_LBS As Double = 2.204
    Private dVolume20, dVolume40, dVolume40HiCube, total, totalWeight As Double

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AddHandler grdCustomerOrder.ItemDataBound, AddressOf grdCustomerOrder_ItemDataBound

        If (Not IsPostBack) Then
            Dim dataList As ShoppingCustomerOrderCollection = ShoppingListService.GetShoppingCustomerOrderCollection()
         
            grdCustomerOrder.DataSource = dataList
            grdCustomerOrder.DataBind()
        End If
    End Sub

    Private Sub InitializedValues(ByVal countryId As Integer)
        Try
            SelectedCountry = CountryService.GetCountry(countryId)
        Catch ex As Exception
        End Try
        If (Not SelectedCountry Is Nothing) Then
            Select Case SelectedCountry.CountryCode
                Case "USA"
                    MeasUnit = "cu ft"
                Case Else
                    MeasUnit = "cbm"
                    'Todo: review later
                    'Case "UK", "ES", "ITA", "NZ", "NO", "TKY"
                    '    hidMeasUnit.Value = "cbm"
                    'Case Else
                    '    hidMeasUnit.Value = "m3"
            End Select
            RoadWeight = SelectedCountry.RoadWeight
        End If
        total = 0
        totalWeight = 0
        If MeasUnit = "cu ft" Then
            dVolume20 = 35 * ONE_VOLUME_CBM_TO_CUFT
            dVolume40 = 70 * ONE_VOLUME_CBM_TO_CUFT
            dVolume40HiCube = 80 * ONE_VOLUME_CBM_TO_CUFT
        ElseIf (MeasUnit = "cbm") Then
            dVolume20 = GetCBMValueByUnitCode("20C")
            dVolume40 = GetCBMValueByUnitCode("40C")
            dVolume40HiCube = GetCBMValueByUnitCode("40HC")
        Else
            dVolume20 = 30
            dVolume40 = 60
            dVolume40HiCube = 76
        End If
    End Sub

    Private Sub grdCustomerOrder_ItemDataBound(ByVal sender As System.Object, ByVal e As System.Web.UI.WebControls.DataListItemEventArgs)
        If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
            Dim lnkDelete As LinkButton = CType(e.Item.FindControl("lnkDelete"), LinkButton)
            lnkDelete.Attributes.Add("onclick", "javascript: return confirm('Are you sure to delete this item?');")

            Dim ltrItemIndex As Literal = CType(e.Item.FindControl("ltrItemIndex"), Literal)
            ltrItemIndex.Text = (e.Item.ItemIndex + 1).ToString()

            Dim pnlFullOrder As Panel = CType(e.Item.FindControl("pnlFullOrder"), Panel)
            Dim pnlPartOrder As Panel = CType(e.Item.FindControl("pnlPartOrder"), Panel)

            Dim orderItem As ShoppingCustomerOrder
            orderItem = CType(CType(e.Item, DataListItem).DataItem, MIMS.WRS.Entities.ShoppingCustomerOrder)
            'InitializedValues(orderItem.DestinationCountryId)

            pnlFullOrder.Visible = orderItem.OrderType
            pnlPartOrder.Visible = Not pnlFullOrder.Visible
        End If
    End Sub

    Protected Sub lnkDelete_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim shoppingOrderId As Int32 = Convert.ToInt32(e.CommandArgument)
        If (ShoppingListService.DeleteFullShoppingOrderById(shoppingOrderId)) Then
            grdCustomerOrder.DataSource = ShoppingListService.GetShoppingCustomerOrderCollection()
            grdCustomerOrder.DataBind()
        End If
    End Sub

    Protected Sub lnkPrint_Command(ByVal sender As Object, ByVal e As CommandEventArgs)
        Dim shoppingOrderId As Int32 = Convert.ToInt32(e.CommandArgument)
        Try
            Dim source As IDataReader = ShoppingListService.GetShoppingCustomerForReportByShoppingOrderId(shoppingOrderId)
            Dim boXml As String = RenderService.GenerateOrdersBOXML(source)
            Dim xslFile As String = Server.MapPath("foxsl/foCustomerOrderReport.xsl")
            Dim foFile As String = Server.MapPath("foTemp/" + String.Format("{0}{1}{2}{3}{4}{5}{6}.fo", DateTime.Now.Year, _
                    DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                    DateTime.Now.Second, DateTime.Now.Millisecond))
            Dim pdfFile As String = String.Format("CustomerOrderReport_{0}{1}{2}{3}{4}{5}{6}.pdf", DateTime.Now.Year, _
                    DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                    DateTime.Now.Second, DateTime.Now.Millisecond)
            Try
                If RenderService.GenerateFO(boXml, xslFile, foFile) Then
                    Dim buffer() As Byte = RenderService.RenderFOtoPDF(foFile)
                    File.Delete(foFile)

                    Response.Clear()
                    Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", HttpUtility.UrlEncode(pdfFile)))
                    Response.AddHeader("Content-Type", "application/pdf")
                    Response.BinaryWrite(buffer)
                    Response.Flush()
                    Response.End()

                End If
            Catch ex As Exception
                Logger.Debug("Failed to render AvailReport PDF", ex)
            End Try
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub btnBack_Click(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnBack.Click
        Response.Redirect("..\StartPage.aspx")
    End Sub

    Protected Sub btnPrint_OnClick(ByVal sender As System.Object, ByVal e As EventArgs) Handles btnPrint.Click
        Try
            ' InitializedValues()
            Dim source As IDataReader = ShoppingListService.GetShoppingCustomerForReport()
            Dim boXml As String = RenderService.GenerateOrdersBOXML(source)
            Dim xslFile As String = Server.MapPath("foxsl/foCustomerOrderReport.xsl")
            Dim foFile As String = Server.MapPath("foTemp/" + String.Format("{0}{1}{2}{3}{4}{5}{6}.fo", DateTime.Now.Year, _
                    DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                    DateTime.Now.Second, DateTime.Now.Millisecond))
            Dim pdfFile As String = String.Format("CustomerOrderReport_{0}{1}{2}{3}{4}{5}{6}.pdf", DateTime.Now.Year, _
                    DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, _
                    DateTime.Now.Second, DateTime.Now.Millisecond)
            Try
                If RenderService.GenerateFO(boXml, xslFile, foFile) Then
                    Dim buffer() As Byte = RenderService.RenderFOtoPDF(foFile)
                    File.Delete(foFile)

                    Response.Clear()
                    Response.AddHeader("Content-Disposition", String.Format("attachment;filename={0}", HttpUtility.UrlEncode(pdfFile)))
                    Response.AddHeader("Content-Type", "application/pdf")
                    Response.BinaryWrite(buffer)
                    Response.Flush()
                    Response.End()

                End If
            Catch ex As Exception
                Logger.Debug("Failed to render AvailReport PDF", ex)
            End Try
        Catch ex As Exception
        End Try
    End Sub

    Protected Function GetDateText(ByVal data As Object) As String
        If data Is DBNull.Value OrElse Convert.ToDateTime(data).Equals(Nulls.NullDate) Then
            Return "&nbsp;"
        Else
            Return Convert.ToDateTime(data).ToString(Config.DateFormat)
        End If
    End Function

    Protected Function GetCustomerName(ByVal title As Object, ByVal familyName As Object, ByVal givenName As Object) As String
        Dim customerName As String = ""

        If Not (title Is DBNull.Value OrElse Convert.ToString(title).Trim() = "") Then
            customerName = Convert.ToString(title).Trim()
        End If
        If Not (givenName Is DBNull.Value OrElse Convert.ToString(givenName).Trim() = "") Then
            customerName = Convert.ToString(IIf(customerName = "", Convert.ToString(givenName).Trim(), customerName & " " & Convert.ToString(givenName).Trim()))
        End If
        If Not (familyName Is DBNull.Value OrElse Convert.ToString(familyName).Trim() = "") Then
            customerName = Convert.ToString(IIf(customerName = "", Convert.ToString(familyName).Trim(), customerName & " " & Convert.ToString(familyName).Trim()))
        End If
        Return customerName
    End Function

    Protected Function GetAddressInfo(ByVal city As Object, ByVal state As Object, ByVal zipCode As Object, ByVal country As Object) As String
        Dim name As String = ""

        If Not (city Is DBNull.Value OrElse Convert.ToString(city).Trim() = "") Then
            name = Convert.ToString(city).Trim()
        End If
        If Not (state Is DBNull.Value OrElse Convert.ToString(state).Trim() = "") Then
            name = Convert.ToString(IIf(name = "", Convert.ToString(state).Trim(), name & ", " & Convert.ToString(state).Trim()))
        End If
        If Not (zipCode Is DBNull.Value OrElse Convert.ToString(zipCode).Trim() = "") Then
            name = Convert.ToString(IIf(name = "", Convert.ToString(zipCode).Trim(), name & ", " & Convert.ToString(zipCode).Trim()))
        End If
        If Not (country Is DBNull.Value OrElse Convert.ToString(country).Trim() = "") Then
            name = Convert.ToString(IIf(name = "", Convert.ToString(country).Trim(), name & ", " & Convert.ToString(country).Trim()))
        End If
        Return name
    End Function

    Protected Function GetQty20Text(ByVal data As Object) As String
        Dim qty20Text As String = ""
        Dim qty20 As Integer = 0
        If Not data Is DBNull.Value Then
            qty20 = Convert.ToInt32(data)
        End If
        Dim temp As String = qty20.ToString(Config.NumericFormat)
        If (temp.Trim() = "") Then
            temp = "0"
        End If
        qty20Text = temp & " x 20' = " & (qty20 * dVolume20).ToString & " " & MeasUnit
        Return qty20Text
    End Function

    Protected Function GetQty40Text(ByVal data As Object) As String
        Dim qty40Text As String = ""
        Dim qty40 As Integer = 0
        If Not data Is DBNull.Value Then
            qty40 = Convert.ToInt32(data)
        End If
        Dim temp As String = qty40.ToString(Config.NumericFormat)
        If (temp.Trim() = "") Then
            temp = "0"
        End If
        qty40Text = temp & " x 40' = " & (qty40 * dVolume40).ToString & " " & MeasUnit
        Return qty40Text
    End Function

    Protected Function GetQty40HCText(ByVal data As Object) As String
        Dim qty40HCText As String = ""
        Dim qty40HC As Integer = 0
        If Not data Is DBNull.Value Then
            qty40HC = Convert.ToInt32(data)
        End If
        Dim temp As String = qty40HC.ToString(Config.NumericFormat)
        If (temp.Trim() = "") Then
            temp = "0"
        End If
        qty40HCText = temp & " x 40'HC = " & (qty40HC * dVolume40HiCube).ToString & " " & MeasUnit
        Return qty40HCText
    End Function

    Protected Function GetTotalVolumeText(ByVal qty20Data As Object, ByVal qty40Data As Object, ByVal qty40HCData As Object) As String
        Dim totalText As String = ""
        Dim qty20 As Double = 0
        Dim qty40 As Double = 0
        Dim qty40HC As Double = 0
        total = 0
        If Not qty20Data Is DBNull.Value Then
            qty20 = Convert.ToInt32(qty20Data) * dVolume20
        End If
        If (qty20 > 0) Then
            total = Convert.ToDouble(qty20)
        End If
        If Not qty40Data Is DBNull.Value Then
            qty40 = Convert.ToInt32(qty40Data) * dVolume40
        End If
        If (qty40 > 0) Then
            total = total + Convert.ToDouble(qty40)
        End If
        If Not qty40HCData Is DBNull.Value Then
            qty40HC = Convert.ToInt32(qty40HCData) * dVolume40HiCube
        End If
        If (qty40HC > 0) Then
            total = total + Convert.ToDouble(qty40HC)
        End If

        If (total <> 0) Then
            totalText = total.ToString(Config.DecimalFormat2) & " " & MeasUnit
        End If
        Return totalText
    End Function

    Protected Function GetTotalWeightText(ByVal qty20Data As Object, ByVal qty40Data As Object, ByVal qty40HCData As Object) As String
        Dim totalText As String = ""
        Dim qty20 As Integer = 0
        Dim qty40 As Integer = 0
        Dim qty40HC As Integer = 0
        totalWeight = 0
        If (Not SelectedCountry Is Nothing) Then
            If Not qty20Data Is DBNull.Value Then
                qty20 = Convert.ToInt32(qty20Data)
            End If
            If (qty20 > 0) Then
                totalWeight = Convert.ToDouble(qty20) * SelectedCountry.RoadWeight
            End If
            If Not qty40Data Is DBNull.Value Then
                qty40 = Convert.ToInt32(qty40Data)
            End If
            If (qty40 > 0) Then
                totalWeight = totalWeight + Convert.ToDouble(qty40) * SelectedCountry.RoadWeight
            End If
            If Not qty40HCData Is DBNull.Value Then
                qty40HC = Convert.ToInt32(qty40HCData)
            End If
            If (qty40HC > 0) Then
                totalWeight = totalWeight + Convert.ToDouble(qty40HC) * SelectedCountry.RoadWeight
            End If
        End If
        If (totalWeight <> 0) Then
            totalText = totalWeight.ToString(Config.DecimalFormat2) & " " & GetMeasUnit()
        End If
        Return totalText
    End Function

    Protected Function GetHalfPalletSpacesText(ByVal data As Object) As String
        Dim halfPalletSpacesText As String = ""
        Dim qty As Integer = 0
        If Not data Is DBNull.Value Then
            qty = Convert.ToInt32(data)
        End If
        If (qty > 0) Then
            halfPalletSpacesText = qty.ToString(Config.NumericFormat)
        End If
        Return halfPalletSpacesText
    End Function

    Protected Function GetFilledVolumeText(ByVal data As Object) As String
        Dim filledVolumeText As String = ""
        Dim qty As Decimal = 0
        If Not data Is DBNull.Value Then
            qty = Convert.ToDecimal(data)
        End If
        If (qty > 0) Then
            filledVolumeText = qty.ToString(Config.DecimalFormat2)
        End If
        Return filledVolumeText
    End Function

    Protected Function IsFullContainerOrder(ByVal data As Object) As Boolean
        Dim bRet As Boolean = True
        If Not data Is DBNull.Value Then
            bRet = Convert.ToBoolean(data)
        End If
        Return bRet
    End Function

    Protected Function GetCompanyNameText(ByVal data As Object) As String
        Dim name As String = Convert.ToString(data)
        If (Not name Is Nothing) Then
            name = name.Replace("'", "~")
        End If
        Return name
    End Function

    Protected Function GetRowClass(ByVal container As Object) As String
        Try
            Dim orderItem As ShoppingCustomerOrder
            orderItem = CType(container, MIMS.WRS.Entities.ShoppingCustomerOrder)
            InitializedValues(orderItem.DestinationCountryId)
        Catch ex As Exception
        End Try

        Dim className As String
        If currentOrder = 1 Then
            currentOrder = 0
            className = "OrderItemRow"
        Else
            currentOrder = 1
            className = "OrderAlternateItemRow"
        End If
        Return className
    End Function

    Private ReadOnly Property Countries() As CountryCollection
        Get
            Try
                If Viewstate("Countries") Is Nothing Then
                    Viewstate("Countries") = CountryService.GetCountries(CountryColumns.CountryName, OrderDirection.ASC)
                End If
            Catch ex As Exception
            End Try
            If Not Viewstate("Countries") Is Nothing Then
                Return CType(Viewstate("Countries"), CountryCollection)
            Else
                Return Nothing
            End If
        End Get
    End Property

    Private Property SelectedCountry() As Country
        Get
            Try
                If Viewstate("SelectedCountry") Is Nothing Then
                    Viewstate("SelectedCountry") = CountryService.GetCountry(RequestContext.CurrentUser.CountryID)
                    If (Not RequestContext.CurrentUser Is Nothing AndAlso RequestContext.CurrentUser.IS_ADMIN) Then
                        For Each item As Country In Countries
                            If (item.CountryCode = "UK" OrElse item.CountryName = "United Kingdom") Then
                                Viewstate("SelectedCountry") = item
                                Exit For
                            End If
                        Next
                    End If
                End If
            Catch ex As Exception
            End Try
            If Not Viewstate("SelectedCountry") Is Nothing Then
                Return CType(Viewstate("SelectedCountry"), Country)
            Else
                Return Nothing
            End If
        End Get
        Set(ByVal Value As Country)
            Viewstate("SelectedCountry") = Value
        End Set
    End Property

    Private Property MeasUnit() As String
        Get
            If Not Viewstate("MeasUnit") Is Nothing Then
                Return CType(Viewstate("MeasUnit"), String)
            Else
                Return "cbm"
            End If
        End Get
        Set(ByVal Value As String)
            Viewstate("MeasUnit") = Value
        End Set
    End Property

    Private Property RoadWeight() As Decimal
        Get
            If Not Viewstate("RoadWeight") Is Nothing Then
                Return CType(Viewstate("RoadWeight"), Decimal)
            Else
                Return 0
            End If
        End Get
        Set(ByVal Value As Decimal)
            Viewstate("RoadWeight") = Value
        End Set
    End Property

    Protected Function GetMeasUnit() As String
        If MeasUnit = "cu ft" Then
            Return "lbs"
        Else
            Return "kg"
        End If
    End Function

    Public Function GetCBMValueByUnitCode(ByVal unitCode As String) As Decimal
        Dim result As Decimal = 0

        If (Not UnitSettingList Is Nothing AndAlso unitCode > "") Then
            For i As Integer = 0 To UnitSettingList.Count - 1
                If (UnitSettingList(i).UnitCode = unitCode) Then
                    Return UnitSettingList(i).CbmValue
                End If
            Next
        End If
        Return result
    End Function
    Private ReadOnly Property UnitSettingList() As UnitSettingCollection
        Get
            Try
                If (Viewstate("UnitSettingList") Is Nothing) Then
                    Viewstate("UnitSettingList") = UnitSettingService.GetUnitSettings()
                End If
            Catch ex As Exception
            End Try
            If Not Viewstate("UnitSettingList") Is Nothing Then
                Return CType(Viewstate("UnitSettingList"), UnitSettingCollection)
            Else
                Return Nothing
            End If
        End Get
    End Property
End Class
